package com.imooc.miaosha.service;

import com.imooc.miaosha.dao.OrderDao;
import com.imooc.miaosha.domain.MiaoshaOrder;
import com.imooc.miaosha.domain.MiaoshaUser;
import com.imooc.miaosha.domain.OrderInfo;
import com.imooc.miaosha.redis.OrderKey;
import com.imooc.miaosha.redis.RedisService;
import com.imooc.miaosha.vo.GoodsVo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author liyuhui
 */
@Service
public class OrderService {
    @Autowired
    OrderDao orderDao;

    @Autowired
    RedisService redisService;

    public MiaoshaOrder getMiaoshaOrderByUserIdGoodsId(long userId, long goodsId) {
//        return orderDao.getMiaoshaOrderByUserIdGoodsId(userId, goodsId);
        //查询缓存
        return redisService.get(OrderKey.getMiaoshaOrderByUidGid,""+userId+"_"+goodsId, MiaoshaOrder.class);
    }

    public OrderInfo getOrderById(long orderId) {
        return orderDao.getOrderById(orderId);
    }


    @Transactional
    public OrderInfo createOrder(MiaoshaUser user, GoodsVo goods) {
        OrderInfo OrderInfo = new OrderInfo();
        OrderInfo.setCreateDate(new Date());
        OrderInfo.setDeliveryAddrId(0L);
        OrderInfo.setGoodsCount(1);
        OrderInfo.setGoodsId(goods.getId());
        OrderInfo.setGoodsName(goods.getGoodsName());
        OrderInfo.setGoodsPrice(goods.getMiaoshaPrice());
        OrderInfo.setOrderChannel(1);
        OrderInfo.setStatus(0);
        OrderInfo.setUserId(user.getId());
        long orderId = orderDao.insert(OrderInfo);

        MiaoshaOrder miaoshaOrder = new MiaoshaOrder();
        miaoshaOrder.setGoodsId(goods.getId());
        miaoshaOrder.setOrderId(orderId);
        miaoshaOrder.setUserId(user.getId());
        orderDao.insertMiaoshaOrder(miaoshaOrder);

        //将秒杀订单放入缓存
        redisService.set(OrderKey.getMiaoshaOrderByUidGid,""+ user.getId() +"_"+ goods.getId(), miaoshaOrder);

        return OrderInfo;
    }


}
